<template>
	<view>
		<view v-for="item in articleList" :key="item.id">
			{{item.title}} -- {{item.author}}
			<uni-icons @tap="articleCollected(item)" :color="item.isCollected?'#f00':''" type="star" :size="40"></uni-icons>
		</view>
	</view>
</template>

<script>
	import {
		findArticleByPage
	} from '@/api/find/index.js'
	import mix from '@/mixins/index.js'
	import Vue from 'vue'
	export default {
		name:"Find",
		mixins:[mix],
		data() {
			return {
			
				start:1,
				limit:10,
				articleList:[]
			};
		},
		onLoad(){
			this.getArticleList()
		},
		methods:{
			async getArticleList(){
				const res = await findArticleByPage(this.start,this.limit)
				// res.data.rows.forEach(ele=>{
				// 	ele.isCollected = false
				// })
				this.articleList = res.data.rows
				this.articleList.forEach(ele=>{
					// ele.isCollected = false
					Vue.set(ele,'isCollected',false)
				})
				
				// 判断
				// 1. 先从本地取收藏列表
				let productCollectedList = uni.getStorageSync('article-collected')
				if(productCollectedList){ // 应用收藏过商品
					this.articleList.forEach(ele=>{
						productCollectedList.forEach(article=>{
							if(ele.id===article.id){
								ele.isCollected = true
							}
						})
					})
					
				}
				
			},
			// 收藏商品
			articleCollected(article){
				if(this.checkIsLogin()){
					// 收藏
			
					// 1. 先从本地取收藏列表
					let productCollectedList = uni.getStorageSync('article-collected')
					if(productCollectedList){ // 应用收藏过商品
						// 判断 当前这个商品是否收藏过
						
						let item = productCollectedList.find(ele=>ele.id===article.id)
						if(item){ // 当前这个商品收藏过
						 
						  let index = productCollectedList.findIndex(ele=>ele.id===article.id)
							productCollectedList.splice(index,1)
							article.isCollected = false
						}else{ // 当前这个商品没有收藏过
						
							productCollectedList.push(article)
							article.isCollected = true
						}
						// 最后需要把 列表 再设置回去
						uni.setStorageSync("article-collected",productCollectedList)
					}else{ // 应用没有收藏过商品
						
						uni.setStorageSync("article-collected",[article])
						article.isCollected = true
					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>

</style>
